import { IRole, RoleParams } from "@/api/role"
import {
  getRoles as getRolesApi,
  removeRole as removeRoleApi,
  addRole as addRoleApi,
  updateRole as updateRoleApi
} from "@/api/role"

export type ActionRoleParams = IRole & {
  pageSize: number
  pageNum: number
}

export const useRoleStore = defineStore("role", () => {
  const state = reactive({
    roles: [] as IRole[],
    count: 0
  })
  const getRoles = async (params: RoleParams) => {
    const res = await getRolesApi(params)
    const { data } = res
    state.roles = data.roles
    state.count = data.count
  }

  const addRole = async (data: ActionRoleParams) => {
    const { pageSize, pageNum, ...params } = data
    const res = await addRoleApi(params)
    if (res.code === 0) {
      getRoles({ pageSize, pageNum })
    }
  }

  const editRole = async (data: ActionRoleParams) => {
    const { pageSize, pageNum, ...params } = data
    const res = await updateRoleApi(params.id, params)
    if (res.code === 0) {
      getRoles({ pageSize, pageNum })
    }
  }

  const removeRole = async (data: ActionRoleParams) => {
    const { pageSize, pageNum, id } = data
    const res = await removeRoleApi(id)
    if (res.code === 0) {
      getRoles({ pageSize, pageNum })
    }
  }

  return {
    state,
    getRoles,
    addRole,
    editRole,
    removeRole
  }
})
